package handler;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import exception.PathVariablePrefixNotLettersException;
import exception.PathVariableSuffixNotNumbersException;

@Controller
public class PathVariableRequestMappingHandler {
    /*
     * RequestMapping的path或value属性可以包含参数，但参数名称必须被“{}”引用，
     * 且该参数须与@PathVariable注解的处理器方法参数相关联
     */
    @RequestMapping(value = "/path/{letter}-{number}", method = RequestMethod.GET)
    public ModelAndView go(
            /*
             * @PathVariable表示方法参数应该被绑定到uri模板变量的注解
             * name或value值必须等于@RequestMapping中的参数值
             */
            @PathVariable(value = "letter") String param1, @PathVariable(name = "number") String param2)
            throws PathVariablePrefixNotLettersException, PathVariableSuffixNotNumbersException {
        for (int index = 0; index < param1.length(); index++) {
            char aChar = param1.charAt(index);
            int charType = Character.getType(aChar);
            // 如果当前字符的类型既不是大写字母又不是小写字母
            if (charType != Character.UPPERCASE_LETTER && charType != Character.LOWERCASE_LETTER) {
                throw new PathVariablePrefixNotLettersException("请求中的letter属性的值必须是纯拉丁字母");
            }
        }
        char[] chars = param2.toCharArray();
        for (char aChar : chars) {
            int charType = Character.getType(aChar);
            // 如果当前字符类型不是数字
            if (charType != Character.DECIMAL_DIGIT_NUMBER) {
                throw new PathVariableSuffixNotNumbersException("请求中的number属性的值必须是纯阿拉伯数字");
            }
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("message", param1);
        modelAndView.addObject(param2);
        return modelAndView;
    }
}
